import axios from 'axios';
import BSPError from './bsperror';

class HttpRequest {
  get(url, params) {
    return this.ajax('get', url, params);
  }

  post(url, params) {
    return this.ajax('post', url, params);
  }

  del(url, params) {
    return this.ajax('delete', url, params);
  }

  put(url, params) {
    return this.ajax('put', url, params);
  }

  upload(url, data, config) {
    return axios.post(url, data, config)
      .then((res) => {
        if (res.data && res.data.code === 10000) {
          return Promise.resolve(res.data);
        } else {
          throw new BSPError(res.data);
        }
      }).catch((err) => {
        if (err instanceof BSPError) {
          return Promise.reject(err);
        } else if (!err.response) { // 网络失败
          return Promise.reject(new BSPError({ code: '00000', msg: '发生了网络错误' }));
        } else {
          if (err.response.status === 404) {
            return Promise.reject(new BSPError({ code: '00000', msg: '请求的资源不存在' }));
          } else {
            let data = err.response.data;
            return Promise.reject(new BSPError(data));
          }
        }
      });
  }

  ajax(method, url, params) {
    return axios[method](url,
      {
        ...params
      })
      .then((res) => {
        if (res.data && res.data.code === 10000) {
          return Promise.resolve(res.data);
        } else {
          throw new BSPError(res.data);
        }
      }).catch((err) => {
        if (err instanceof BSPError) {
          return Promise.reject(err);
        } else if (!err.response) { // 网络失败
          return Promise.reject(new BSPError({ code: '00000', msg: '发生了网络错误' }));
        } else {
          if (err.response.status === 404) {
            return Promise.reject(new BSPError({ code: '00000', msg: '请求的资源不存在' }));
          } else if (err.response.status === 403 || err.response.status === 401) {
            let data = err.response.data;
            return Promise.reject(new BSPError(data));
          } else {
            let data = err.response.data;
            return Promise.reject(new BSPError(data));
          }
        }
      });
  }
}

export default new HttpRequest();